/**
 * User: C1008010
 * Date: 13-6-15
 * Time: 下午4:23
 * To change this template use File | Settings | File Templates.
 */
(function($){
    $.fn.extend({
        _showDefectJudgeDialog : function(options){
        	var letterCol = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z'];
            var new_logic_flg = "N",
            	df = {},
                gdefectAry = [],
                showDefAry = [];

            df.defaults = {
                callbackFn : null
            };
            df.config = $.extend(df.defaults, options || {});

            df.VAL = {
                NORMAL     : "0000000",
                T_XPINQCOD : "XPINQCOD",
                T_XPLAYOUT : "XPLAYOUT",
                T_XPDEFECT : "XPDEFECT",
                TBL_ID_M   : "_showDefectJudgeDialogMtrlDefTbl",
                TBL_ID_P   : "_showDefectJudgeDialogProcDefTbl",
                TD_CLS_M   : "_showDefectJudgeDialogMtrlDefTdCls",
                TD_CLS_P   : "_showDefectJudgeDialogProcDefTdCls"
            };

            df.controlQ = {
                crDialog      : $("#_defectJudgeDialog"),
                cancelBnt     : $("#_defectJudgeDialog_cancelBtn"),
                okBtn         : $("#_defectJudgeDialog_selectBtn"),
                prdSeqIdTxt   : $("#_defectJudgeDialog_prdSeqIdTxt"),
                selectDefBtn  : $("#_defectJudgeDialog_selectDefBtn"),
                delDefBtn     : $("#_defectJudgeDialog_delDefBtn"),
                cancelJgeBtn  : $("#_defectJudgeDialog_cancelJgeBtn"),
                selectAllBtn  : $("#_defectJudgeDialog_selectAllBtn"),
                unSelectBtn   : $("#_defectJudgeDialog_unSelectedBtn"),
                defPosTxt     : $("#_defectJudgeDialog_defectPositionTxt"),
                groupIdTxt    : $("#_defectJudgeDialog_groupIdTxt"),
                remarkTxt     : $("#_defectJudgeDialog_remarkTxt"),
                cusDefDiv     : $("#_defectJudgeDialog_cusMtrlDefectDiv"),
                processDefDiv : $("#_defectJudgeDialog_processDefectDiv"),
                runFlgSp      : $("#_defectJudgeDialog_runFlgSp"),
                rowIdSp       : $("#_defectJudgeDialog_rowIdSp"),
                judgeOKRadio  : $("#_defectJudgeDialog_judgeRadioOK"),
                judgeNGRadio  : $("#_defectJudgeDialog_judgeRadioNG"),
                judgeSCRadio  : $("#_defectJudgeDialog_judgeRadioSC"),
                judgeGKRadio  : $("#_defectJudgeDialog_judgeRadioGK"),
                judgeLZRadio  : $("#_defectJudgeDialog_judgeRadioLZ"),
                judgeRMRadio  : $("#_defectJudgeDialog_judgeRadioRM"),
                judgeRWRadio  : $("#_defectJudgeDialog_judgeRadioRW"),
                okHide        : $("#okHide"),
                ngHide        : $("#ngHide"),
                scHide        : $("#scHide"),
                lzHide        : $("#lzHide"),
                gkHide        : $("#gkHide"),
                rmHide        : $("#rmHide"),
                rwHide        : $("#rwHide"),
                gdSelect      : $("#gdSelect"),
                ownSelect     : $("#ownSelect"),
                selectCount   : $("#_selectCount"),
                noSelectCount : $("#_noSelectCount"),
                tft_side      : $("#tft_side"),
                cf_side       : $("#cf_side"),
                defZoneDiv    : $("#_defectJudgeDialog_defZoneDiv"),
                layoutZoneDiv : $("#_defectJudgeDialog_layoutZoneDiv"),
                layoutTab     : $("#_defectJudgeDialog_layoutTab"),
                tftLayoutDiv  : $("#_defectJudgeDialog_tftLayoutDiv"),
                cfLayoutDiv   : $("#_defectJudgeDialog_cfLayoutDiv"),
                mainGrd       : {
                    grdId     : $("#_defectJudgeDialog_defInfoGrd")   ,
                    grdPgText : "#_defectJudgeDialog_defInfoPg"       ,
                    fatherDiv : $("#_defectJudgeDialog_defInfoDiv")
                }
            };

            df.toolFunc = {
                iniCrDialog : function(){
                    df.controlQ.crDialog.modal({
                        backdrop:true ,
                        keyboard:true,
                        show:false
                    });

                    df.controlQ.prdSeqIdTxt.val(options.prd_seq_id);
                    df.controlQ.defPosTxt.val("");
                    df.controlQ.rowIdSp.attr("value", options.rowId);
                    //20150128确认清空dialog中的备注信息，不做显示
                    df.controlQ.remarkTxt.val("");
                    //1100不可修改,1400可修改group id
                    df.controlQ.groupIdTxt.val("");
                    df.controlQ.groupIdTxt.val(options.group_id);
                    if(options.groupFlg){
                    	df.controlQ.groupIdTxt[0].disabled = false;
                    }else{
                    	df.controlQ.groupIdTxt[0].disabled = true;
                    }
                    //带出产品的备注
                    df.controlQ.remarkTxt.val(options.ds_recipe_id);
                    $('#_defectJudgeDialog_layoutTab a:first').tab('show');

                    gdefectAry = options.oldDefList;
                    showDefAry = options.showDefList;
                    
                    new_logic_flg = options.new_logic_flg;
                    console.log("new_logic_flg is " + options.new_logic_flg);
//                    prd_seq_grd = options.prd_seq_grd;
                    prd_seq_grd_t = options.prd_seq_grd_t;
                    prd_seq_grd_c = options.prd_seq_grd_c;
                    
                    console.log("judge_grade is %s", options.judge_grade);
                    if(new_logic_flg == "Y"){
                    	df.controlQ.cancelJgeBtn.show();
                    }else{
                    	df.controlQ.cancelJgeBtn.hide();
                    }
                    
                    //Load prd grade from GDGP
                    var inTrxObjM = {
                        trx_id    : df.VAL.T_XPINQCOD,
                        action_flg: 'I',
                        data_cate : 'GDGP',
                    };
                    if (options.cus_id){
                    	inTrxObjM.cus_id = options.cus_id;
                    }
                    var gdCompare = function(gd1, gd2) {
                    	   if (gd1.data_ext < gd2.data_ext) {
                    	       return -1;
                    	   } else if (gd1.data_ext > gd2.data_ext) {
                    	       return 1;
                    	   } else {
                    	       return 0;
                    	   }
                    	}
                    var outTrxObjM = comTrxSubSendPostJson(inTrxObjM);
                    console.log(outTrxObjM.oary);
                    console.log(outTrxObjM.oary[0].data_ext);
                    outTrxObjM.oary.sort(gdCompare);
                    console.log(outTrxObjM.oary);
                    if( outTrxObjM.rtn_code === df.VAL.NORMAL) {
                    	_setSelectDate(outTrxObjM.tbl_cnt, outTrxObjM.oary, "data_ext", "data_ext", "#gdSelect", true);
                    	df.controlQ.gdSelect.val(options.judge_grade).trigger("change");;
                    } 
                    //init own
                    df.controlQ.ownSelect.empty();
                    df.controlQ.ownSelect.append("<option value='' > </option>");
                    df.controlQ.ownSelect.append("<option value='I' >來料</option>");
                    df.controlQ.ownSelect.append("<option value='P' >制程</option>");
                    df.controlQ.ownSelect.val(options.own_typ).trigger("change");;
                },
                iniGridInfo : function(){
                    var grdInfoCMDef = [
                        {name: 'defect_code',     index: 'defect_code',     label: DEF_CODE_TAG,     width: 60,hidden:true},
                        {name: 'defDsc',          index: 'defDsc',          label: '不良描述',          width: 120},
                        {name: 'defect_side',     index: 'defect_side',     label: '不良侧',           width: 80},
                        {name: 'position',        index: 'position',        label: DEF_POSITION_TAG, width: 80,hidden:true},
                        {name: 'positionview',        index: 'positionview',        label: DEF_POSITION_TAG, width: 80},
                        {name: 'defect_cnt',      index: 'defect_cnt',      label: '不良数量',          width: 80},
                        {name: 'def_typ',         index: 'def_typ',         label: '不良类型',          width: 80},
                        {name: 'ox_show_typ',     index: 'ox_show_typ',     label: 'X显示',            width: 80,hidden:true}
                    ];
                    df.controlQ.mainGrd.grdId.jqGrid({
                        url:"",
                        datatype:"local",
                        mtype:"POST",
                        height:90,
                        width:560,
                        shrinkToFit:false,
                        scroll:true,
                        rownumWidth : true,
                        resizable : true,
                        rowNum:40,
                        loadonce:true,
                        fixed:true,
                        viewrecords:true,
                        multiselect : true,
                        cmTemplate: { sortable: false },
                        colModel: grdInfoCMDef
                    });

                    setGridInfo(showDefAry, "#_defectJudgeDialog_defInfoGrd");
                    df.toolFunc.addPositionView();
                },
                defectTdClickFnc :function(obj){
                    if( $(obj).hasClass("btn-primary")){
                        $(obj).removeClass("btn-primary");
                    }else{
                        $("#_defectJudgeDialog_defZoneDiv" + " ." + "btn-primary").removeClass("btn-primary");
                        $(obj).addClass("btn-primary");
                    }
                },
                iniDefTable : function(tblID, tdClass, tbl_cnt, oary, fatherDiv, type){
                    var defectCnt,
                        defectCntFilter,
                        defectAry = [],
                        defectAryFilter = [],
                        remainTdCnt,//表格td余数
                        tableHtml,
                        i,
                        col = 6,
                        defect_pep = options.pep_lvl;

                    if("" == defect_pep){
                        console.log("Pep lvl is null, no defect!");
                        return false;
                    }

                    if( 1 === tbl_cnt){
                        defectAry.push(oary);
                    }else{
                        defectAry = oary;
                    }
                    defectCnt = defectAry.length;

                    for(i = 0; i < defectCnt; i ++ ){
                        if("Y" == defectAry[i].ext_4[defect_pep-1]){
                            defectAryFilter.push(defectAry[i]);
                        }
                    }
                    defectCntFilter = defectAryFilter.length;

                    fatherDiv.empty();

                    tableHtml = "<table id="+ tblID +" class='table table-bordered table-condensed'>" + "<tr>";
                    for(i = 1; i <= defectCntFilter; i++){
                        tableHtml = tableHtml + "<td class="+ tdClass +" id=defectTd_" + type + "_" + i +
                            " name="+ defectAryFilter[i-1].data_id +
                            " ox="+ defectAryFilter[i-1].ext_1 +">" +
                            defectAryFilter[i-1].data_ext +
                            "</td>";
                        if(i!=0 && i%col ===0){
                        	tableHtml = tableHtml + "</tr><tr>";
                        }
                    }

                    //如果不足col的倍数，补充空白
                    remainTdCnt = defectCntFilter%col;
                    if( remainTdCnt !== 0 ){
                        for(i = 0; i < col-remainTdCnt; i++ ){
                            tableHtml = tableHtml +'<td></td>';
                        }
                    }
                    tableHtml = tableHtml + "</tr></table>";
                    $(tableHtml).appendTo(fatherDiv);
                    $("#"+tblID).addClass("noMarginBottomCss");
                    $("#" + tblID + " ." + tdClass).click(function(){
                        df.toolFunc.defectTdClickFnc(this);
                    });
                },
                loadDefData : function(){
                    var inTrxObjM,
                        inTrxObjP,
                        outTrxObjM,
                        outTrxObjP,
                        tbl_cntM,
                        tbl_cntP;

                    //Load mtrl defect
                    inTrxObjM = {
                        trx_id    : df.VAL.T_XPINQCOD,
                        action_flg: 'I',
                        data_cate : 'DFCT',
                        ext_2     : 'Y'
                    };
                    if (options.cus_id){
                    	inTrxObjM.cus_id = options.cus_id;
                    }
                    outTrxObjM = comTrxSubSendPostJson(inTrxObjM);
                    if( outTrxObjM.rtn_code === df.VAL.NORMAL) {
                        tbl_cntM = parseInt( outTrxObjM.tbl_cnt, 10);
                        df.toolFunc.iniDefTable(df.VAL.TBL_ID_M, df.VAL.TD_CLS_M, tbl_cntM, outTrxObjM.oary, df.controlQ.cusDefDiv, "M");
                    }

                    if(options.proc_id !== "JBIC"){
                        //Load process defect
                        inTrxObjP = {
                            trx_id    : df.VAL.T_XPINQCOD,
                            action_flg: 'I',
                            data_cate : 'DFCT',
                            ext_3     : 'Y'
                        };
                        if (options.cus_id){
                        	inTrxObjP.cus_id = options.cus_id;
                        }
                        outTrxObjP = comTrxSubSendPostJson(inTrxObjP);
                        if( outTrxObjP.rtn_code === df.VAL.NORMAL) {
                            tbl_cntP = parseInt( outTrxObjP.tbl_cnt, 10);
                            df.toolFunc.iniDefTable(df.VAL.TBL_ID_P, df.VAL.TD_CLS_P, tbl_cntP, outTrxObjP.oary, df.controlQ.processDefDiv, "P");
                        }
                    }
                },
                layoutTdClickFnc :function(obj, tft_td_class, cf_td_class){
                    var curZoneSelCnt;

                    curZoneSelCnt = ($(obj.parentElement.parentElement).find(".btn-success")).length;
                    if(0 === curZoneSelCnt){
                        if($(obj).hasClass(tft_td_class)){
                            $("." + cf_td_class).removeClass("btn-success");
                        }else if($(obj).hasClass(cf_td_class)){
                            $("." + tft_td_class).removeClass("btn-success");
                        }
                    }
                    $(obj).toggleClass("btn-success");
                    df.toolFunc.selectCount();
                },
                createLayoutZone : function(rowCnt, colCnt, layoutDivObj, sideType, isCf) {
                    var tdClass,
                        tbId,
                        tdID,
                        tableHtml,
                        r, c,
                        row, col,
                        totalCnt,
                        tft_td_class ="dj_tft_td",
                        cf_td_class ="dj_cf_td";
                    totalCnt = 0;

                    if("T" === sideType){
                        tdClass = tft_td_class;
                        tbId = "dj_tft_tb";
                        tdID = "dj_tft_td_";
                    }else{
                        tdClass = cf_td_class;
                        tbId = "dj_cf_tb";
                        tdID = "dj_cf_td_";
                    }
                    row = parseInt( rowCnt, 10 );
                    col = parseInt( colCnt, 10 );

                    tableHtml = "<table id="+ tbId +" class='table table-bordered table-condensed'>";
                    for( r=1; r<=row; r++ ){
                        tableHtml += "<tr>";
                        for( c=1; c<=col; c++ ){
                            totalCnt++;
                            if( true !== isCf){//TFT
                            	var tft_strNo = (r-1)*col + (col - c + 1); //公式:(x-1)*row + y,如layout是13*6,粒是4*3，结果为(4-1)*13+6
                            	if(new_logic_flg == "Y" && prd_seq_grd_t.substr(tft_strNo-1,1) != "O" && prd_seq_grd_t.substr(tft_strNo-1,1) != "0"){
                            		//tableHtml += "<td style=" + "color:#F00" + " value="+ totalCnt +" id="+tdID+ r +"_"+ (col - c + 1) +" class="+ tdClass +" id>"+ r +"*"+ (col - c + 1) +"</td>";
                            		tableHtml += "<td style=" + "color:#F00" + " layout="+ r +"*"+ (col - c + 1) +"   value="+ totalCnt +" id="+tdID+ r +"_"+ (col - c + 1) +" class="+ tdClass +" id>"+letterCol[col - c] + ""+ r +"</td>";

                            	}else{
                            		//tableHtml += "<td value="+ totalCnt +" id="+tdID+ r +"_"+ (col - c + 1) +" class="+ tdClass +" id>"+ r +"*"+ (col - c + 1) +"</td>";
                            		tableHtml += "<td layout="+ r +"*"+ (col - c + 1) +"   value="+ totalCnt +" id="+tdID+ r +"_"+ (col - c + 1) +" class="+ tdClass +" id>"+letterCol[col - c] + ""+ r +"</td>";
                            	}
                            }else{//CF
                            	var cf_strNo = (r-1)*col + c;
                            	if(new_logic_flg == "Y" && prd_seq_grd_c.substr(cf_strNo-1,1) != "O" && prd_seq_grd_c.substr(cf_strNo-1,1) != "0"){
                            		//tableHtml += "<td style=" + "color:#F00" + " value="+ totalCnt +" id="+tdID+ r +"_"+ c +" class="+ tdClass +" id>"+ r +"*"+ c +"</td>";
                            		tableHtml += "<td style=" + "color:#F00" + " layout="+ r +"*"+ c +"   value="+ totalCnt +" id="+tdID+ r +"_"+ c +" class="+ tdClass +" id>"+ letterCol[c-1] + "" + r +"</td>";

                            	}else{
                            		//tableHtml += "<td  value="+ totalCnt +" id="+tdID+ r +"_"+ c +" class="+ tdClass +" id>"+ r +"*"+ c +"</td>";
                            		tableHtml += "<td layout="+ r +"*"+ c +"   value="+ totalCnt +" id="+tdID+ r +"_"+ c +" class="+ tdClass +" id>"+ letterCol[c-1] + "" + r +"</td>";
                            	}
                            }
                        }
                        tableHtml += "</tr>";
                    }

                    tableHtml += "</table>";
                    $(tableHtml).appendTo(layoutDivObj);
                    $("."+tdClass).click(function(){
                        df.toolFunc.layoutTdClickFnc(this, tft_td_class, cf_td_class);
                    });
                },
                loadLayout : function(){
                    df.controlQ.tftLayoutDiv.empty();
                    df.controlQ.cfLayoutDiv.empty();
                    df.toolFunc.createLayoutZone(options.y_axis_cnt, options.x_axis_cnt, df.controlQ.tftLayoutDiv, "T", false);
                    df.toolFunc.createLayoutZone(options.y_axis_cnt, options.x_axis_cnt, df.controlQ.cfLayoutDiv, "C", true);
                    df.toolFunc.selectCount();
                },
                selectCount : function(){
                	var SelCnt = ($(".tab-pane.active.layoutZone").find(".btn-success")).length;
                	var row = parseInt( options.y_axis_cnt, 10 );
                    var col = parseInt( options.x_axis_cnt, 10 );
                    var noSelCnt = row * col - SelCnt;
                    df.controlQ.selectCount.html("已选中粒数：" + SelCnt);
                    df.controlQ.noSelectCount.html("未选粒数："  + noSelCnt);
                },
                layoutChg : function(layout){
                	var letterCol = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z'];
                	var i = parseInt(layout.substring(0,layout.indexOf('*')),10);
                	var j = parseInt(layout.substring(layout.indexOf('*')+1),10);
                	return (letterCol[j-1]+""+i);
                },
                addPositionView : function(){
                    var crGrid = df.controlQ.mainGrd.grdId; 
                    var ids = crGrid.jqGrid('getDataIDs');
                    for(var i = 0;i < ids.length; i++){
                    	var layout = crGrid.jqGrid("getCell",ids[i],"position");
                    	crGrid.jqGrid("setCell",ids[i],"positionview",df.toolFunc.layoutChg(layout));
                    }
                }
            };
            
            df.btnFunc = {
                cancelBtnFunc : function(){
                    df.controlQ.crDialog.modal("hide");

                    if (typeof df.config.callbackFn === 'function') { // 确保类型为函数类型
                        df.config.callbackFn(null);
                    }
                },
                okBtnFunc : function(){
                    var defectInfo,
                        judge_grade,
                        own_typ,
                        remark,
                        group_id;

//                    judge_grade = $("input[name='_defectJudgeDialog_judgeRadios']:checked").val();
                    judge_grade = df.controlQ.gdSelect.val().trim();
                    own_typ     = df.controlQ.ownSelect.val().trim();
                    if(options.cus_id == "007" && (judge_grade == "SC" || judge_grade == "RM") && !own_typ){
                        showErrorDialog("","007客户，SC或者RM等级必须选择权责归属！");
                        return false;
                    }
                    remark      = df.controlQ.remarkTxt.val().trim();
                    group_id    = df.controlQ.groupIdTxt.val().trim();
                    defectInfo = {
                        prd_seq_id  : options.prd_seq_id,
                        rowId       : df.controlQ.rowIdSp.attr("value"),
                        judge_grade : judge_grade,
                        own_typ     : own_typ
                    };
                    
                    if(new_logic_flg == "Y"){
                    	var defAry = [];
                    	var rowIds = df.controlQ.mainGrd.grdId.jqGrid('getDataIDs');
                    	for(var i=0; i<rowIds.length; i++){
                    		var rowData = df.controlQ.mainGrd.grdId.jqGrid("getRowData",rowIds[i]);
                    		if(rowData["ox_show_typ"]=="undefined"){
                    			rowData["ox_show_typ"]="";
                    		}
                        	defAry.push({
                                defect_cnt  : parseInt(rowData["defect_cnt"],10),
                                defect_code : rowData["defect_code"],
                                defDsc      : rowData["defDsc"],
                                defect_side : rowData["defect_side"],
                                //positionview: rowData["positionview"],
                                position    : rowData["position"],
                                def_typ     : rowData["def_typ"],
                                ox_show_typ : rowData["ox_show_typ"]
                            });
                    	}
                    	defectInfo.defectAry = defAry;
                    }else{
                    	defectInfo.defectAry = options.oldDefList;
                    }
                    
                    if(remark){
                    	defectInfo.remark = remark;
                    }
                    
                    if(group_id){
                    	defectInfo.group_id = group_id;
                    }
                    
                    df.controlQ.crDialog.modal("hide");

                    if (typeof df.config.callbackFn === 'function') { // 确保类型为函数类型
                        df.config.callbackFn(defectInfo);
                    }
                },
                selectDefBtnFunc : function(){
                    'use strict';
                    gdefectAry = options.oldDefList;
                    showDefAry = options.showDefList;
                    //I don't know why gdefectAry will be [] here, because of closure?? or in dialog??
                    //Same in deleteDefBtnFunc
                    //There many other similar issue(many of them has been fixed in ugly way)
                    //If you find the reason, please tell me: jipengdeyouxiang@qq.com
                    var i,
                        total_def_index,
                        len,
                        defectObj,
                        defectCode,
                        defectox,
                        defectDsc,
                        defectSide,
                        defectPositions,
                        tmpPositon, 
                        objId,
                        objIdAry,
                        def_typ,
                        def_cnt = 0;

                    //Get defect
                    defectObj = $($("#_defectJudgeDialog_defZoneDiv" + " .btn-primary")[0]);//这中选择不好
                    defectCode = defectObj.attr("name");
                    defectox = defectObj.attr("ox");
                    defectDsc = defectObj.html();
                    if(!defectDsc){
                        showErrorDialog("","请选择不良!");
                        return false;
                    }
                    objId = defectObj.attr("id");
                    objIdAry = objId.split("_");
                    def_typ = objIdAry[1];
                    //By side & position
                    defectPositions = $("#_defectJudgeDialog_tftLayoutDiv").find(".btn-success");
                    if(0 === defectPositions.length){
                        defectPositions = $("#_defectJudgeDialog_cfLayoutDiv").find(".btn-success");
                        if(0 === defectPositions.length){
                            showErrorDialog("","请选择异常位置！");
                            return false;
                        }else{
                            defectSide = "C";
                        }
                    }else{
                        defectSide = "T";
                    }

                    for( i = 0, len = defectPositions.length; i < len; i++){
                        tmpPositon =$(defectPositions[i]).attr("layout");
                        for( total_def_index = gdefectAry.length - 1; total_def_index >= 0; total_def_index--){
                        	if(gdefectAry[total_def_index].position === tmpPositon &&
                        			gdefectAry[total_def_index].proc_id != "JBYZ"){
                            	def_cnt = def_cnt + parseInt(gdefectAry[total_def_index].defect_cnt,10);
                            }
                        	if(total_def_index == 0 && def_cnt > 0 ){ 
                                showErrorDialog('', '[' + tmpPositon + ']位置上已经判定过不良，不允许再次判定！');
                                return false;
                            }
                        }
                    }
                    if(options.proc_id == "JBYZ"){
                    	for( total_def_index = showDefAry.length - 1;
                        total_def_index >= 0; total_def_index--){
                    		if(showDefAry[total_def_index].position === tmpPositon){
                    			def_cnt = def_cnt + parseInt(showDefAry[total_def_index].defect_cnt,10);
                    		}
	                   		if(total_def_index == 0 && def_cnt > 0 ){ 
	                           showErrorDialog('', '[' + tmpPositon + ']位置上已经判定过不良，不允许再次判定！');
	                           return false;
	                       }
	                   }
                    }
                    for( i = 0, len = defectPositions.length; i < len; i++){
                        gdefectAry.push({
                            defect_cnt  : 1,
                            defect_code : defectCode,
                            defDsc      : defectDsc,
                            defect_side : defectSide,
                            position    : $(defectPositions[i]).attr("layout"),
                            def_typ     : def_typ,
                            proc_id     : options.proc_id
                        });
                        showDefAry.push({
                            defect_cnt  : 1,
                            defect_code : defectCode,
                            defDsc      : defectDsc,
                            defect_side : defectSide,
                            position    : $(defectPositions[i]).attr("layout"),
                            def_typ     : def_typ,
                            ox_show_typ : defectox
                        });
                        $(defectPositions[i]).removeClass("btn-success");
                    }

                    defectObj.removeClass("btn-primary");

                    setGridInfo(showDefAry, "#_defectJudgeDialog_defInfoGrd");
                    df.toolFunc.addPositionView();
                    return false;
                },
                deleteDefBtnFunc : function(){
                    gdefectAry = options.oldDefList;
                    showDefAry = options.showDefList;
                    var i, j,k,
                        curGrid,
                        selIds,
                        curRowData;

                    curGrid = df.controlQ.mainGrd.grdId;

                    selIds = curGrid.jqGrid("getGridParam","selarrrow");
                    for ( i = selIds.length - 1; i >= 0; i-- ) {
                        curRowData = curGrid.jqGrid("getRowData", selIds[i]);
                        for ( j = gdefectAry.length - 1; j >= 0; j-- ) {
                            if( curRowData.defect_code === gdefectAry[j].defect_code &&
                                curRowData.defect_side === gdefectAry[j].defect_side &&
                                parseInt( curRowData.defect_cnt, 10) === parseInt( gdefectAry[j].defect_cnt, 10) ){
                                if (gdefectAry[j].hasOwnProperty('position')) {
                                    if (curRowData.position === gdefectAry[j].position) {
                                        gdefectAry.splice(j, 1);
                                        break;
                                    }
                                } else {
                                    gdefectAry.splice(j, 1);
                                    break;
                                }
                            }
                        }
                        for ( k = showDefAry.length - 1; k >= 0; k-- ) {
                            if( curRowData.defect_code === showDefAry[k].defect_code &&
                                curRowData.defect_side === showDefAry[k].defect_side &&
                                parseInt( curRowData.defect_cnt, 10) === parseInt( showDefAry[k].defect_cnt, 10) ){
                                if (showDefAry[k].hasOwnProperty('position')) {
                                    if (curRowData.position === showDefAry[k].position) {
                                    	showDefAry.splice(k, 1);
                                        break;
                                    }
                                } else {
                                	showDefAry.splice(k, 1);
                                    break;
                                }
                            }
                        }
                    }

                    setGridInfo(showDefAry, "#_defectJudgeDialog_defInfoGrd");
                    df.toolFunc.addPositionView();
                    return false;
                },
                cancelJgeBtnFunc : function(){
                	var defectPositions,
                		defectSide,
                		tmpPositon,
                		prd_seq_id,
                		iary = [];
                	
                	gdefectAry = options.oldDefList;
                	showDefAry = options.showDefList;
                	prd_seq_id = options.prd_seq_id;
                    defectPositions = $("#_defectJudgeDialog_tftLayoutDiv").find(".btn-success");
                    if(0 === defectPositions.length){
                        defectPositions = $("#_defectJudgeDialog_cfLayoutDiv").find(".btn-success");
                        if(0 === defectPositions.length){
                            showErrorDialog("","请选择需要取消判定的位置！");
                            return false;
                        }
                    }
                    
                    for( var i = 0; i < defectPositions.length; i++){
                        tmpPositon = $(defectPositions[i]).attr("layout");
                        iary.push({
                        	def_code_lc : tmpPositon
                        });
                    }
                    var inTrxObj = {
                        trx_id    : df.VAL.T_XPDEFECT,
                        action_flg: 'I',
                        prd_seq_id : prd_seq_id,
                        iary : iary
                    };
                    var outTrxObj = comTrxSubSendPostJson(inTrxObj);
                    if( outTrxObj.rtn_code === df.VAL.NORMAL) {
                    	if(outTrxObj.def_cnt > 1){
                    		for(var i=0; i<outTrxObj.def_cnt; i++){
                                for(var total_def_index = showDefAry.length - 1;
	 		                       total_def_index >= 0; total_def_index--){
	 		                       if(showDefAry[total_def_index].position === outTrxObj.defList[i].position){
			                    	   if(showDefAry[total_def_index].defect_cnt > 0){
		 		                           showErrorDialog('', '当站[' + outTrxObj.defList[i].position + ']位置上已经判定过不良，不允许取消判定，请直接删除！');
		 		                           return false;
			                    	   }else{
				                           showErrorDialog('', '[' + outTrxObj.defList[i].position + ']位置上已经取消判定不良，不允许重复取消判定！');
				                           return false;
			                    	   }
	 		                       }
	 		                   }
                    		}
                    		for(var i=0; i<outTrxObj.def_cnt; i++){
                                gdefectAry.push({
                                    defect_cnt : outTrxObj.defList[i].defect_cnt,
                                    defect_code : outTrxObj.defList[i].defect_code,
                                    defDsc : outTrxObj.defList[i].defDsc,
                                    defect_side : outTrxObj.defList[i].defect_side,
                                    position : outTrxObj.defList[i].position,
                                    def_typ : outTrxObj.defList[i].def_typ
                                });
                                showDefAry.push({
                                    defect_cnt : outTrxObj.defList[i].defect_cnt,
                                    defect_code : outTrxObj.defList[i].defect_code,
                                    defDsc : outTrxObj.defList[i].defDsc,
                                    defect_side : outTrxObj.defList[i].defect_side,
                                    position : outTrxObj.defList[i].position,
                                    def_typ : outTrxObj.defList[i].def_typ,
                                    ox_show_typ : outTrxObj.defList[i].ox_show_typ
                                });
                    		}
                    	}else if(outTrxObj.def_cnt == 1){
                            for(var total_def_index = showDefAry.length - 1;
		                       total_def_index >= 0; total_def_index--){
		                       if(showDefAry[total_def_index].position === outTrxObj.defList.position){
		                    	   if(showDefAry[total_def_index].defect_cnt > 0){
			                           showErrorDialog('', '[' + outTrxObj.defList.position + ']位置上已经判定过不良，不允许取消判定，请直接删除！');
			                           return false;
		                    	   }else{
			                           showErrorDialog('', '[' + outTrxObj.defList.position + ']位置上已经取消判定不良，不允许重复取消判定！');
			                           return false;
		                    	   }
		                       }
		                   }
                            gdefectAry.push({
                                defect_cnt : outTrxObj.defList.defect_cnt,
                                defect_code : outTrxObj.defList.defect_code,
                                defDsc : outTrxObj.defList.defDsc,
                                defect_side : outTrxObj.defList.defect_side,
                                position : outTrxObj.defList.position,
                                def_typ : outTrxObj.defList.def_typ
                            });
                            showDefAry.push({
                                defect_cnt : outTrxObj.defList.defect_cnt,
                                defect_code : outTrxObj.defList.defect_code,
                                defDsc : outTrxObj.defList.defDsc,
                                defect_side : outTrxObj.defList.defect_side,
                                position : outTrxObj.defList.position,
                                def_typ : outTrxObj.defList.def_typ,
                                ox_show_typ : outTrxObj.defList.ox_show_typ
                            });
                    	}
                    	setGridInfo(showDefAry, "#_defectJudgeDialog_defInfoGrd");
                    	df.toolFunc.addPositionView();
                    	
                    	$(".tab-pane.active.layoutZone").find("td.btn-success").removeClass("btn-success");
                    }
                    return false;
                },
                //Not this button
                clearDefFunc : function(){
                    gdefectAry = [];
                },
                //全选
                selectAllFunc:function(){
                	$(".tab-pane.active.layoutZone").find("td").addClass("btn-success");
                	df.toolFunc.selectCount();
                },
                //反选
                unSelectFunc:function(){
                	$(".tab-pane.active.layoutZone").find("td.btn-success").removeClass("btn-success");
                	df.toolFunc.selectCount();
                }
            };

            df.iniButtonAction = function(){
                df.controlQ.cancelBnt.unbind("click");
                df.controlQ.cancelBnt.click(function(){
                    df.btnFunc.cancelBtnFunc();
                });

                df.controlQ.okBtn.unbind("click");
                df.controlQ.okBtn.click(function(){
                    df.btnFunc.okBtnFunc();
                });

                df.controlQ.selectDefBtn.unbind("click");
                df.controlQ.selectDefBtn.click(function(){
                    df.btnFunc.selectDefBtnFunc();
                });

                df.controlQ.delDefBtn.unbind("click");
                df.controlQ.delDefBtn.click(function(){
                    df.btnFunc.deleteDefBtnFunc();
                });
                
                df.controlQ.cancelJgeBtn.unbind("click");
                df.controlQ.cancelJgeBtn.click(function(){
                	df.btnFunc.cancelJgeBtnFunc();
                });
                
                df.controlQ.selectAllBtn.on("click",df.btnFunc.selectAllFunc);
                
                df.controlQ.unSelectBtn.on("click",df.btnFunc.unSelectFunc);
                
                df.controlQ.tft_side.on("click",df.toolFunc.selectCount);
                df.controlQ.cf_side.on("click",df.toolFunc.selectCount);
            };

            df.toolFunc.iniCrDialog();
            df.toolFunc.iniGridInfo();
            df.toolFunc.loadDefData();
            df.toolFunc.loadLayout();

            df.iniButtonAction();
            $('#_defectJudgeDialog_layoutTab a').click(function (e) {
                e.preventDefault();
                $(this).tab('show');
            });

            df.controlQ.crDialog.modal("show");
            df.btnFunc.clearDefFunc();
        }
    });
})(jQuery);


